#ifndef __COMM_HPP__
#define __COMM_HPP__

#include <iostream>
#include <string>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <assert.h>

using namespace std;

#define Path "fifo"
#define Mode 0666

class Fifo
{
public:
    Fifo(const string &pathname = Path)
        : _pathname(pathname)
    {
        int n = mkfifo(_pathname.c_str(), Mode);
        if (n == 0)
        {
            cout << "mkfifo success" << endl;
        }
        else
        {
            cout << "mkfifo failed ,errno:" << errno << " errstring:" << strerror(errno) << endl;
        }
    }

    ~Fifo()
    {
        int n = unlink(_pathname.c_str());
        if (n == 0)
        {
            cout << "unlink success" << endl;
        }
        else
        {
            cout << "unlink failed ,errno:" << errno << " errstring:" << strerror(errno) << endl;
        }
    }

private:
    string _pathname;
};

class Syns
{
public:
    Syns()
        : rfd(-1), wfd(-1)
    {
    }

    void OpenReadOrDie()
    {
        rfd = open(Path, O_RDONLY);
        if (rfd < 0)
            exit(1);
    }

    void OpenWriteOrDie()
    {
        wfd = open(Path, O_WRONLY);
        if (wfd < 0)
            exit(1);   
    }

    bool Wait()
    {
        bool ret = true;
        uint32_t c = 0;
        ssize_t n = read(rfd, &c, sizeof(uint32_t));
        if (n == sizeof(uint32_t))
        {
            cout << "serve wake up begin read shm..." << endl;
        }
        else if (n == 0)
        {
            ret = false;
        }
        else
        {
            ret = false;
        }

        return ret;
    }

    void WakeUp()
    {
        uint32_t c = 0;
        ssize_t n = write(wfd, &c, sizeof(c));
        assert(n == sizeof(uint32_t));

        cout << "wake up serve..." << endl;
    }

    ~Syns()
    {
    }

private:
    int wfd;
    int rfd;
};

#endif